package com.quanyan.club.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.quanyan.activity.entity.ActivityInfo;
import com.quanyan.activity.service.ActivityOpenService;
import com.quanyan.club.constants.ClubConstants;
import com.quanyan.club.entity.RespClubBaseInfo;
import com.quanyan.club.entity.db.*;
import com.quanyan.club.entity.vo.msg.ActivityRelatedMsg;
import com.quanyan.club.entity.vo.resp.RespClubActivity;
import com.quanyan.club.entity.vo.resp.RespClubFinanceBillDetail;
import com.quanyan.club.mapper.*;
import com.quanyan.club.service.CppService;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.exception.BizException;
import com.quanyan.common.http.HttpClientUtils;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.common.utils.GsonUtils;
import com.quanyan.common.utils.Limit;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.im.entity.req.ModifyIMGroup;
import com.quanyan.im.entity.req.ReqAddOrDelGroupMember;
import com.quanyan.im.entity.req.ReqCreateIMGroup;
import com.quanyan.im.entity.resp.RespIMGroup;
import com.quanyan.messagepush.entity.*;
import com.quanyan.messagepush.enums.BoxName;
import com.quanyan.messagepush.enums.BoxType;
import com.quanyan.messagepush.enums.IdType;
import com.quanyan.messagepush.enums.MsgType;
import com.quanyan.user.response.RespUserInfoBase;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by zhuo.shi on 2016/7/20.
 */
@Service
public class CppServiceImpl implements CppService {

    private static Logger logger = LoggerFactory.getLogger(CppServiceImpl.class);

    @Value("${im.service.baseurl}")
    private String imBaseURL;
    @Value("${message.push.service.url}")
    public String messagePushServiceUrl;
    @Autowired
    private TbClubMapper clubMapper;
    @Autowired
    private TbClubMemberMapper clubMemberMapper;
    @Autowired
    private TbSignUserMapper signUserMapper;
    @Autowired
    private TbClubActivityMapper tbclubActivityMapper;
    @Autowired
    private TbActivityPosterMapper tbActivityPosterMapper;
    @Autowired
    private ActivityOpenService activityOpenService;
    @Autowired
    private TbOrderMapper orderMapper;

    private static String LARK_LOGO = "lark_icon.png";

    @Override
    public String createIMGroup(ReqCreateIMGroup reqCreateIMGroup) {

        try {
            String postJson = JSON.toJSONString(reqCreateIMGroup);
            String result = HttpClientUtils.postJson(imBaseURL + "/createGroup.api", postJson);
            logger.warn("C++返回参数" + result);
            if (StringUtil.isBlankOrNull(result)) {
                return null;
            }
            RespIMGroup resp = GsonUtils.jsonStrToEntity(result, RespIMGroup.class);
            if (resp != null && resp.getRet()) {
                JSONObject groupInfo = resp.getData().getJSONArray("groupinfo").getJSONObject(0);
                return groupInfo.getString("groupid");
            }
        } catch (Exception e) {
            logger.error("请求创建俱乐部聊天室错误：" + e.getMessage());
        }
        return null;
    }

    @Override
    public void modifyGroup(ModifyIMGroup modifyIMGroup){
        try {
            String postJson = JSON.toJSONString(modifyIMGroup);
            String result = HttpClientUtils.postJson(imBaseURL + "/modifyGroup.api", postJson);
            logger.warn("修改群组，返回：" + result);
        } catch (Exception e) {
            logger.error("修改群组错误：" + e.getMessage());
        }
    }

    @Override
    public boolean addOrDelIMGroupMember(int uid,int moudleId, String groupid, List<Integer> uidList, boolean add) {
        ReqAddOrDelGroupMember req = new ReqAddOrDelGroupMember();
        req.setExtid(moudleId);
        req.setCurrentUid(uid);
        req.setGroupid(groupid);
        req.setMembers(uidList);
        String url = imBaseURL;
        if (add) {
            url += "/addMembers.api";
        } else {
            url += "/deleteMembers.api";
        }
        try {
            String result = HttpClientUtils.postJson(url, JSON.toJSONString(req));
            logger.warn("加入俱乐部成员到聊天组，请求：" + JSON.toJSONString(req)+ "，返回：" + result);
            if (StringUtil.isBlankOrNull(result)) {
                return false;
            }
            RespIMGroup resp = GsonUtils.jsonStrToEntity(result, RespIMGroup.class);
            if (resp != null && (resp.getRet() || resp.getErrcode() == -11040)) {  //-11040已经加入群组
                return true;
            }
        } catch (Exception e) {
            logger.error("请求加入或删除俱乐部聊天室成员错误：" + e.getMessage());
        }
        return false;
    }

    @Override
    @Async
    public void pushWithdrawNotifyMessage(TbClubWithdrawalsApply apply, boolean success, String reason) {
        String message = "";
        if (success) {
            message = "你有一笔提现" + apply.getMoney() + "元已成功打款至你绑定的"
                    + (apply.getAccountType() == ClubConstants.WITHDRAW_BY_ALIPAY ? "支付宝" : "微信") + apply.getWithdrawalsName()+ "，请留意到账情况。";
        } else {
            message = "您申请的" + ((apply.getAccountType() == ClubConstants.WITHDRAW_BY_ALIPAY)?apply.getWithdrawalsAccount():"") + "账户资金提现处理未成功，请检查绑定的提现账号是否有误。";
        }
        TbClub club = clubMapper.selectByPrimaryKey(apply.getClubId());

        ReqPushMessage reqPushMessage = new ReqPushMessage();
        PushMessage pushMessage = new PushMessage();
        pushMessage.setTag(BoxName.CLUB.value() + System.currentTimeMillis());
        Alert alert = new Alert();
        alert.setBody("俱乐部消息：" + message);
        pushMessage.setAlert(alert);

        pushMessage.setTo(Arrays.asList(club.getUid()));
        pushMessage.setLogo(LARK_LOGO);
        pushMessage.setLogoUrl("");
        Payload payload = new Payload();
        payload.setBoxType(BoxType.CLUB_MSG.value());
        payload.setMsgType(MsgType.JUMP_MSG.value());
        payload.setTitle(message);
        payload.setImg(club.getLogoUrl());
        payload.setTimestamp(System.currentTimeMillis());

        payload.setUrl("/api/club/widthdraw/recordlist");         //点击整行消息跳转提现记录列表
        Jump jump = new Jump();
        jump.setIdType(IdType.CLUB_WITHDRAW_RECORD_PAGE.value());
        Map<String, Object> jumMap = new HashMap<>();
        jumMap.put("toindex", 1);
        jumMap.put("clubId", club.getId());
        jump.setParam(jumMap);
        payload.setJump(jump);

        pushMessage.setPayload(payload);

        reqPushMessage.setMsgList(Arrays.asList(pushMessage));

        this.pushMsg(reqPushMessage);
    }

    //接受加入俱乐部邀请，发送通知给邀请人
    @Async
    public void pushAcceptJoinClubInvite(TbClub club, RespUserInfoBase userInfo, List<Integer> to, int larkAppId) {

        String message = userInfo.getNickName() + "已经接受你的邀请，加入俱乐部" + club.getClubName() + "!";

        ReqPushMessage reqPushMessage = new ReqPushMessage();
        PushMessage pushMessage = new PushMessage();
        pushMessage.setTag(BoxName.CLUB.value() + System.currentTimeMillis());
        Alert alert = new Alert();
        alert.setBody("俱乐部消息：" + message);
        pushMessage.setAlert(alert);

        pushMessage.setTo(to);
        pushMessage.setLogo(LARK_LOGO);
        pushMessage.setLogoUrl("");
        Payload payload = new Payload();
        payload.setBoxType(BoxType.CLUB_MSG.value());
        payload.setMsgType(MsgType.JUMP_MSG.value());
        payload.setTitle(message);
        payload.setImg(club.getLogoUrl());
        payload.setTimestamp(System.currentTimeMillis());

        payload.setUrl("/api/user/information/index");         //点击整行消息跳转个人主页
        Jump jump = new Jump();
        jump.setIdType(IdType.USER_HOME_PAGE.value());
        Map<String, Object> jumMap = new HashMap<>();
        jumMap.put("uid", userInfo.getUid());
        jumMap.put("original", 2);
        jump.setParam(jumMap);
        payload.setJump(jump);

        pushMessage.setPayload(payload);
        reqPushMessage.setMsgList(Arrays.asList(pushMessage));
        reqPushMessage.setAppId(larkAppId);
        this.pushMsg(reqPushMessage);
    }


    //用户加入俱乐部，推送消息给俱乐部所有成员
    @Async
    @Override
    public void pushJoinClub2AllMember(TbClub club, RespUserInfoBase userInfo, List<Integer> to) {

        String message = userInfo.getNickName() + "用户，加入了" + club.getClubName() + "俱乐部!";

        ReqPushMessage reqPushMessage = new ReqPushMessage();
        PushMessage pushMessage = new PushMessage();
        pushMessage.setTag(BoxName.CLUB.value() + System.currentTimeMillis());
        Alert alert = new Alert();
        alert.setBody("俱乐部消息：" + message);
        pushMessage.setAlert(alert);

        pushMessage.setTo(to);
        pushMessage.setLogo(LARK_LOGO);
        pushMessage.setLogoUrl("");
        Payload payload = new Payload();
        payload.setBoxType(BoxType.CLUB_MSG.value());
        payload.setMsgType(MsgType.JUMP_MSG.value());
        payload.setTitle(message);
        payload.setImg(userInfo.getIcon());
        payload.setTimestamp(System.currentTimeMillis());

        payload.setUrl("/api/user/information/index");         //点击整行消息跳转个人主页
        Jump jump = new Jump();
        jump.setIdType(IdType.USER_HOME_PAGE.value());
        Map<String, Object> jumMap = new HashMap<>();
        jumMap.put("uid", userInfo.getUid());
        jumMap.put("original", 2);
        jump.setParam(jumMap);
        payload.setJump(jump);

        pushMessage.setPayload(payload);
        reqPushMessage.setMsgList(Arrays.asList(pushMessage));

        this.pushMsg(reqPushMessage);
    }


    /**
     * 俱乐部成员申请加入俱乐部，管理员邀请加入俱乐部，消息推送
     */
    @Override
    @Async
    public void pushClubMemberJoinMsg(RespUserInfoBase user, TbClub club, List<Integer> to, String remark,
                                      boolean invite, int inviteType, boolean apply) {
        String str = "";
        int type = 1;
        if (invite) {
            str = "邀请";
            type = 2;
        }
        if (apply) {
            str = "申请";
            type = 1;
        }
        Integer clubId = club.getId();

        ReqPushMessage reqPushMessage = new ReqPushMessage();
        PushMessage pushMessage = new PushMessage();
        pushMessage.setTag(BoxName.CLUB.value() + System.currentTimeMillis());
        Alert alert = new Alert();
        alert.setBody("俱乐部消息：" + user.getNickName() + str + "您加入\"" + club.getClubName() + "\"俱乐部");
        pushMessage.setAlert(alert);
        pushMessage.setTo(to);                          //被邀请人 或 申请人 uid
        pushMessage.setLogo(LARK_LOGO);
        pushMessage.setLogoUrl("");
        Payload payload = new Payload();
        payload.setBoxType(BoxType.CLUB_MSG.value());
        payload.setMsgType(MsgType.OPERATION_MSG.value());
        payload.setNickname(user.getNickName());  //被邀请人 或 申请人昵称
        payload.setImg(user.getIcon());            //被邀请人 或 申请人头像
        payload.setTitle(user.getNickName() + str + "加入俱乐部\"" + club.getClubName() + "\"");
        payload.setBody(remark);
        if (apply) {                //申请，点击整行消息跳转申请入会的用户主页
            payload.setUrl("/api/user/information/index");

            Operation operation = new Operation();
            Jump jump = new Jump();
            Map<String, Object> jumMap = new HashMap<>();
            jumMap.put("uid", user.getUid());
            jumMap.put("original", 2);
            jump.setIdType(IdType.USER_HOME_PAGE.value());
            jump.setParam(jumMap);
            payload.setJump(jump);

            List<Option> options = new ArrayList<>();
            Option option1 = new Option();
            option1.setType(1);
            option1.setText("同意");
            Action action1 = new Action();
            action1.setActionUrl("/api/club/member/agree/join");
            Map<String, Object> map1 = new HashMap<>();
            map1.put("type", 1);
            map1.put("clubId", String.valueOf(clubId));
            map1.put("invitedUid", user.getUid());

            action1.setParam(map1);
            option1.setAction(action1);
            options.add(option1);
            Option option2 = new Option();
            option2.setType(2);
            option2.setText("拒绝");
            Action action2 = new Action();
            action2.setActionUrl("/api/club/member/disagree/join");
            Map<String, Object> map2 = new HashMap<>();
            map2.put("type", 1); //管理员拒绝
            map2.put("clubId", String.valueOf(clubId));
            map2.put("refuseUid", user.getUid());
            action2.setParam(map2);
            option2.setAction(action2);
            options.add(option2);

            operation.setOption(options);
            payload.setOperation(operation);

        } else if (invite) {       //邀请，点击整行跳转到俱乐部主页
            payload.setUrl("/api/club/system/detail");
            Operation operation = new Operation();
            Jump jump = new Jump();
            jump.setIdType(IdType.CLUB_DETAIL_PAGE.value());
            Map<String, Object> jumMap = new HashMap<>();
            jumMap.put("clubId", clubId);
            jump.setParam(jumMap);
            payload.setJump(jump);

            List<Option> options = new ArrayList<>();
            Option option1 = new Option();
            option1.setType(4);
            option1.setText("立即加入");
            Action action = new Action();
            action.setActionUrl("/api/club/member/agree/join");
            Map<String, Object> map = new HashMap<>();
            map.put("type", String.valueOf(type));
            map.put("clubId", String.valueOf(clubId));
            map.put("invitedUid", user.getUid());
            action.setParam(map);
            option1.setAction(action);
            options.add(option1);

            operation.setOption(options);
            payload.setOperation(operation);
        }
        payload.setTimestamp(System.currentTimeMillis());
        pushMessage.setPayload(payload);
        reqPushMessage.setMsgList(Arrays.asList(pushMessage));
        logger.warn("------------ pushMsg=" + JSON.toJSONString(reqPushMessage));
        this.pushMsg(reqPushMessage);
    }

    /**
     * 管理员不同意用户申请加入，管理员踢俱乐部成员，俱乐部成员退出推送消息
     *
     * @param uid 退出的成员的用户uid，或者管理员uid(踢人，不同意的时候)
     */
    @Override
    @Async
    public void pushClubMemberOutMsg(String imgUrl, int uid, int clubId, String msg, List<Integer> to, int type, int larkAppId) {
        ReqPushMessage reqPushMessage = new ReqPushMessage();
        PushMessage pushMessage = new PushMessage();
        pushMessage.setTag(BoxName.CLUB.value() + System.currentTimeMillis());
        Alert alert = new Alert();
        alert.setBody("俱乐部消息：" + msg);
        pushMessage.setAlert(alert);
        pushMessage.setTo(to);
        pushMessage.setLogo(LARK_LOGO);
        pushMessage.setLogoUrl("");
        Payload payload = new Payload();
        payload.setBoxType(BoxType.CLUB_MSG.value());
        payload.setMsgType(MsgType.JUMP_MSG.value());
        payload.setTitle(msg);
        payload.setImg(imgUrl);
        payload.setTimestamp(System.currentTimeMillis());
        if (type == 3) {     //管理员不同意加入
            payload.setUrl("/api/club/system/detail");      //跳转到俱乐部详情页
            Jump jump = new Jump();
            jump.setIdType(IdType.CLUB_DETAIL_PAGE.value());
            Map<String, Object> jumMap = new HashMap<>();
            jumMap.put("clubId", clubId);
            jump.setParam(jumMap);
            payload.setJump(jump);
        }
        else {     //1 用户自己退出，2 被管理员提出，用户自己不同意加入
            payload.setUrl("/api/user/information/index");         //点击整行消息跳转用户主页
            Jump jump = new Jump();
            jump.setIdType(IdType.USER_HOME_PAGE.value());
            Map<String, Object> jumMap = new HashMap<>();
            jumMap.put("uid", uid);
            jumMap.put("original", 2);
            jump.setParam(jumMap);
            payload.setJump(jump);
        }

        pushMessage.setPayload(payload);
        reqPushMessage.setMsgList(Arrays.asList(pushMessage));
        reqPushMessage.setAppId(larkAppId);
        this.pushMsg(reqPushMessage);
    }

    /**
     * 成功加入俱乐部后，推送消息，开始聊天入口
     */
    @Override
    @Async
    public void pushJoinClubMsg(TbClub club, List<Integer> to, RespUserInfoBase user, int larkAppId) {
        ReqPushMessage reqPushMessage = new ReqPushMessage();
        reqPushMessage.setAppId(larkAppId);
        PushMessage pushMessage = new PushMessage();
        pushMessage.setTag(BoxName.CLUB.value() + System.currentTimeMillis());
        Alert alert = new Alert();
        alert.setBody("俱乐部消息：" + "恭喜您成功加入了\"" + club.getClubName() + "\"，快去和大家打声招呼吧！");
        pushMessage.setAlert(alert);
        pushMessage.setTo(to);                          //被邀请人 或 申请人 uid
        pushMessage.setLogo(LARK_LOGO);
        pushMessage.setLogoUrl("");
        Payload payload = new Payload();
        payload.setBoxType(BoxType.CLUB_MSG.value());

        payload.setImg(club.getLogoUrl());       //俱乐部logo
        payload.setTitle("恭喜您加入了\"" + club.getClubName() + "\"，快去和大家打声招呼吧！");
        payload.setBody("");
        payload.setUrl("/api/club/system/detail");

        if (!StringUtil.isBlankOrNull(club.getImGroupid())) {
            Operation operation = new Operation();
            operation.setId(String.valueOf(club.getId()));
            operation.setIdType(IdType.DATESPORT_CHAT.value());

            List<Option> options = new ArrayList<>();
            Option option1 = new Option();
            option1.setType(3);
            option1.setText("开始聊天");
            options.add(option1);
            operation.setOption(options);

            Map<String, Object> map1 = new HashMap<>();
            map1.put("groupId", String.valueOf(club.getImGroupid())); //俱乐部聊天室id
            map1.put("nick", club.getClubName());
            map1.put("avatar", club.getLogoUrl());
            map1.put("uid", club.getId());
            /*String imMsg = null;
            if(user.getGender() == 1)//
            {
                imMsg = "大家好！我是阳光帅气的" + user.getNickName() + "！";

            }
            else
            {
                imMsg = "大家好，我是花儿般美丽的" + user.getNickName() + "！";
            }
            map1.put("imMsg", imMsg);*/
            operation.setParam(map1);

            payload.setMsgType(MsgType.OPERATION_MSG.value());

            payload.setOperation(operation);
        }else {
            payload.setMsgType(MsgType.JUMP_MSG.value());
        }
        Jump jump = new Jump();
        jump.setIdType(IdType.CLUB_DETAIL_PAGE.value());
        Map<String, Object> jumMap = new HashMap<>();
        jumMap.put("clubId", club.getId());
        jump.setParam(jumMap);
        payload.setJump(jump);


        payload.setTimestamp(System.currentTimeMillis());
        pushMessage.setPayload(payload);
        reqPushMessage.setMsgList(Arrays.asList(pushMessage));

        this.pushMsg(reqPushMessage);
    }

    /**
     * 活动开始前半小时推送消息，活动将要开始
     */
    @Async
    @Override
    public void pushActivityStartingMsg(ActivityInfo activityInfo, List<Integer> to) {
        String msg = "您报名参加的活动“" + activityInfo.getName() + "”将于"
                + DateUtils.convertDateToString(activityInfo.getStartTime())
                + "开始了哦，您准备好了吗？";
        ReqPushMessage reqPushMessage = new ReqPushMessage();
        PushMessage pushMessage = new PushMessage();
        pushMessage.setTag(BoxName.CLUB.value() + System.currentTimeMillis());
        Alert alert = new Alert();
        alert.setBody("俱乐部消息：" + msg);
        pushMessage.setAlert(alert);
        pushMessage.setTo(to);
        pushMessage.setLogo(LARK_LOGO);
        pushMessage.setLogoUrl("");
        Payload payload = new Payload();
        payload.setBoxType(BoxType.CLUB_MSG.value());
        payload.setMsgType(MsgType.JUMP_MSG.value());
        payload.setTitle(msg);
        Integer activityId = activityInfo.getId();
        TbClubActivityExample example = new TbClubActivityExample();
        example.createCriteria().andActivityIdEqualTo(activityId);
        List<TbClubActivity> clubActivities = tbclubActivityMapper.selectByExample(example);
        if (clubActivities == null || clubActivities.size() <= 0) {
            return;
        }
        TbClubActivity clubActivity = clubActivities.get(0);
        TbClub club = clubMapper.selectByPrimaryKey(clubActivity.getClubId());
        payload.setImg(club.getLogoUrl());
        payload.setTimestamp(System.currentTimeMillis());
        payload.setUrl("/api/club/activity/activityDetail");      //跳转到俱乐部活动详情页
        Jump jump = new Jump();
        jump.setIdType(IdType.CLUB_ACTIVITY_DETAIL_PAGE.value());
        Map<String, Object> jumMap = new HashMap<>();
        jumMap.put("activityId", activityId);
        jump.setParam(jumMap);
        payload.setJump(jump);
        pushMessage.setPayload(payload);
        reqPushMessage.setMsgList(Arrays.asList(pushMessage));
        this.pushMessageToC(reqPushMessage);
    }

    /**
     * 活动取消时通知发布活动的管理员
     */
    @Async
    @Override
    public void pushCancelActivity(RespClubActivity respClubActivity, int larkAppId) {
        //推送内容
        respClubActivity.getLogoUrl();
        String msg = "您已取消了" +
                DateUtils.convertDateToString(respClubActivity.getStartTime())
                + "时间" + respClubActivity.getClubName() + "俱乐部举办的" +
                respClubActivity.getName() + "活动，查看详情";
        ReqPushMessage reqPushMessage = new ReqPushMessage();
        PushMessage pushMessage = new PushMessage();
        pushMessage.setTag(BoxName.CLUB.value() + System.currentTimeMillis());
        Alert alert = new Alert();
        alert.setBody("俱乐部消息：" + msg);
        pushMessage.setAlert(alert);
        List<Integer> to = new ArrayList<Integer>();
        to.add(respClubActivity.getUid());//推送给发布俱乐部活动的人
        pushMessage.setTo(to);
        pushMessage.setLogo(LARK_LOGO);
        pushMessage.setLogoUrl("");
        Payload payload = new Payload();
        payload.setBoxType(BoxType.CLUB_MSG.value());
        payload.setMsgType(MsgType.JUMP_MSG.value());
        payload.setTitle(msg);
        //俱乐部LOGO
        payload.setImg(respClubActivity.getLogoUrl());
        //当前时间
        payload.setTimestamp(System.currentTimeMillis());
        payload.setUrl("/api/club/activity/activityDetail");      //跳转到俱乐部活动详情页
        Jump jump = new Jump();
        jump.setIdType(IdType.CLUB_ACTIVITY_DETAIL_PAGE.value());
        Map<String, Object> jumMap = new HashMap<>();
        jumMap.put("activityId", respClubActivity.getActivityId());
        jump.setParam(jumMap);
        payload.setJump(jump);
        pushMessage.setPayload(payload);
        reqPushMessage.setMsgList(Arrays.asList(pushMessage));
        reqPushMessage.setAppId(larkAppId);
        this.pushMsg(reqPushMessage);
    }

    /**
     * 收费活动取消时通知参加该活动的成员
     */
    @Async
    @Override
    public void pushCancelActivityToMember(RespClubActivity respClubActivity, String refundOrderNo, int larkAppId) {
        //推送内容
        respClubActivity.getLogoUrl();
        String msg = "您报名参加的活动“" + respClubActivity.getName() +
                "“，俱乐部管理员已经取消，系统将自动返还您的报名费，请注意查收。";
        ReqPushMessage reqPushMessage = new ReqPushMessage();
        PushMessage pushMessage = new PushMessage();
        pushMessage.setTag(BoxName.CLUB.value() + System.currentTimeMillis());
        Alert alert = new Alert();
        alert.setBody("俱乐部消息：" + msg);
        pushMessage.setAlert(alert);
        //推送给参加该活动的成员
        TbSignUserExample example = new TbSignUserExample();
        TbSignUserExample.Criteria criteria = example.createCriteria();
        criteria.andActivityIdEqualTo(respClubActivity.getActivityId());
        criteria.andIsCancelEqualTo(0);//未取消
        criteria.andStatusEqualTo(1);//有效
        List<TbSignUser> tbSignUserList = signUserMapper.selectByExample(example);
        List<Integer> to = new ArrayList<Integer>();
        TbOrderExample orderExample = new TbOrderExample();
        orderExample.createCriteria().andOrderNoEqualTo(refundOrderNo);
        List<TbOrder> orders = orderMapper.selectByExample(orderExample);
        if(CollectionUtils.isNotEmpty(orders))
        {
            TbOrder order = orders.get(0);
            to.add(order.getOrderUid());
        }
        pushMessage.setTo(to);
        pushMessage.setLogo(LARK_LOGO);
        pushMessage.setLogoUrl("");
        Payload payload = new Payload();
        payload.setBoxType(BoxType.CLUB_MSG.value());
        payload.setMsgType(MsgType.JUMP_MSG.value());
        payload.setTitle(msg);
        //俱乐部LOGO
        payload.setImg(respClubActivity.getLogoUrl());
        //当前时间
        payload.setTimestamp(System.currentTimeMillis());
        payload.setUrl("/api/club/activity/activityOrderDetail");      //跳转到俱乐部活动订单详情页
        Jump jump = new Jump();
        jump.setIdType(IdType.CLUB_ACTIVITY_ORDER_DETAIL_PAGE.value());
        Map<String, Object> jumMap = new HashMap<>();
        jumMap.put("activityId", respClubActivity.getActivityId());
        jumMap.put("businessOrderNo", refundOrderNo);
        jump.setParam(jumMap);
        payload.setJump(jump);
        pushMessage.setPayload(payload);
        reqPushMessage.setMsgList(Arrays.asList(pushMessage));
        reqPushMessage.setAppId(larkAppId);

        this.pushMessageToC(reqPushMessage);
    }

    /**
     * 收费活动取消时通知补报名的成员
     */
    @Async
    @Override
    public void pushCancelActivityToMainderMember(RespClubActivity respClubActivity, Integer uid) {
        //推送内容
        respClubActivity.getLogoUrl();
        String msg = "您报名参加的活动“" + respClubActivity.getName() +
                "“，管理员已经取消，系统将自动返还您的报名费。";
        ReqPushMessage reqPushMessage = new ReqPushMessage();
        PushMessage pushMessage = new PushMessage();
        pushMessage.setTag(BoxName.CLUB.value() + System.currentTimeMillis());
        Alert alert = new Alert();
        alert.setBody("俱乐部消息：" + msg);
        pushMessage.setAlert(alert);
        Payload payload = new Payload();
        payload.setBoxType(BoxType.CLUB_MSG.value());
        payload.setMsgType(MsgType.NOTIFY_MSG.value());
        payload.setTitle(msg);
        payload.setImg(respClubActivity.getLogoUrl());
        payload.setTimestamp(System.currentTimeMillis());
        pushMessage.setPayload(payload);
        pushMessage.setTo(Arrays.asList(uid));
        reqPushMessage.setMsgList(Arrays.asList(pushMessage));
        this.pushMsg(reqPushMessage);

    }

    /**
     * 用户取消报名通知发布活动的人
     * @param respClubActivity
     * @param orderUid
     */
    @Async
    @Override
    public void pushCancelActivityOrder(RespClubActivity respClubActivity, Integer orderUid, int orderId)
    {
        //推送内容
        respClubActivity.getLogoUrl();
        TbSignUserExample userExample = new TbSignUserExample();
        userExample.createCriteria().andOrderUserIdEqualTo(orderUid)
                .andActivityIdEqualTo(respClubActivity.getActivityId()).andOrderIdEqualTo(orderId);
        List<TbSignUser> signUsers = signUserMapper.selectByExample(userExample);
        String username = null;
        if(signUsers.size() > 0)
        {
            TbSignUser tbSignUser = signUsers.get(0);
            username = tbSignUser.getName();
        }
        String msg = username + "用户取消参加您于" +
                DateUtils.convertDateToString(respClubActivity.getStartTime())
                + "时间举办的" + respClubActivity.getName() + "活动，查看详情";
        ReqPushMessage reqPushMessage = new ReqPushMessage();
        PushMessage pushMessage = new PushMessage();
        pushMessage.setTag(BoxName.CLUB.value() + System.currentTimeMillis());
        Alert alert = new Alert();
        alert.setBody("俱乐部消息：" + msg);
        pushMessage.setAlert(alert);
        List<Integer> to = new ArrayList<Integer>();
        to.add(respClubActivity.getUid());//推送给发布俱乐部活动的人
        pushMessage.setTo(to);
        pushMessage.setLogo(LARK_LOGO);
        pushMessage.setLogoUrl("");
        Payload payload = new Payload();
        payload.setBoxType(BoxType.CLUB_MSG.value());
        payload.setMsgType(MsgType.JUMP_MSG.value());
        payload.setTitle(msg);
        //俱乐部LOGO
        payload.setImg(respClubActivity.getLogoUrl());
        //当前时间
        payload.setTimestamp(System.currentTimeMillis());
        payload.setUrl("/api/club/activity/activityDetail");      //跳转到俱乐部活动详情页
        Jump jump = new Jump();
        jump.setIdType(IdType.CLUB_ACTIVITY_DETAIL_PAGE.value());
        Map<String, Object> jumMap = new HashMap<>();
        jumMap.put("activityId", respClubActivity.getActivityId());
        jump.setParam(jumMap);
        payload.setJump(jump);
        pushMessage.setPayload(payload);
        reqPushMessage.setMsgList(Arrays.asList(pushMessage));
        this.pushMsg(reqPushMessage);
    }

    /**
     * 俱乐部活动自动结算后推送给活动发布者
     */
    @Async
    @Override
    public void pushActivityAutoSettle(ActivityRelatedMsg activityRelatedMsg,
                                       RespClubFinanceBillDetail respClubFinanceBillDetail)
    {
        TbClub club = clubMapper.selectByPrimaryKey(activityRelatedMsg.getClubId());
        if (club == null)
        {
            logger.warn("没有这个俱乐部,req:" + activityRelatedMsg.getClubId());
            return;
        }

        String message = club.getClubName() + "俱乐部创建的" +
                activityRelatedMsg.getActivityName() + "活动已于" +
                DateUtils.convertDateToString(new Date()) + "完成系统自动结算，查看详情";

        ReqPushMessage reqPushMessage = new ReqPushMessage();
        PushMessage pushMessage = new PushMessage();
        pushMessage.setTag(BoxName.CLUB.value() + System.currentTimeMillis());
        Alert alert = new Alert();
        alert.setBody("俱乐部消息：" + message);
        pushMessage.setAlert(alert);

        pushMessage.setTo(activityRelatedMsg.getToUid());
        pushMessage.setLogo(LARK_LOGO);
        pushMessage.setLogoUrl("");
        Payload payload = new Payload();
        payload.setBoxType(BoxType.CLUB_MSG.value());
        payload.setMsgType(MsgType.JUMP_MSG.value());
        payload.setTitle(message);
        payload.setImg(club.getLogoUrl());
        payload.setTimestamp(System.currentTimeMillis());

        payload.setUrl("/api/club/activity/settlementDetailList");         //活动账单详情
        Jump jump = new Jump();
        jump.setIdType(IdType.ACTIVITY_ACCOUNT_DETAIL.value());
        Map<String, Object> jumMap = new HashMap<>();
        jumMap.put("serialNo", respClubFinanceBillDetail.getSerialNo());
        jumMap.put("amount", respClubFinanceBillDetail.getAmount());
        jumMap.put("onlineAmount", respClubFinanceBillDetail.getOnlineAmount());
        jumMap.put("offlineAmount", respClubFinanceBillDetail.getOfflineAmount());
        jumMap.put("activityId", respClubFinanceBillDetail.getActivityId());
        jumMap.put("activityName", respClubFinanceBillDetail.getActivityName());
        jumMap.put("incomeFrom", respClubFinanceBillDetail.getIncomeFrom());
        jumMap.put("numberOfPeople", respClubFinanceBillDetail.getNumberOfPeople());
        jumMap.put("createTime", respClubFinanceBillDetail.getCreateTime());
        jumMap.put("createrName", respClubFinanceBillDetail.getCreaterName());
        if(null != activityRelatedMsg.getPosterId())
        {
            TbActivityPoster poster =
                    tbActivityPosterMapper.selectByPrimaryKey(activityRelatedMsg.getPosterId());
            jumMap.put("avatar", poster.getUrl());
        }
        jump.setParam(jumMap);
        payload.setJump(jump);

        pushMessage.setPayload(payload);
        reqPushMessage.setMsgList(Arrays.asList(pushMessage));

        this.pushMsg(reqPushMessage);
    }

    /**
     * 俱乐部活动自动结算后推送给活动发布者
     */
    @Async
    @Override
    public void pushActivitySignUp(RespClubActivity respClubActivity, Integer currentUid, int larkAppId)
    {
        //推送内容
        Integer activityId = respClubActivity.getActivityId();
        String msg = "您已成功报名" + respClubActivity.getName() + "活动，请于"
                + DateUtils.convertDateToString(respClubActivity.getStartTime()) + "准时参加！";
        ReqPushMessage reqPushMessage = new ReqPushMessage();
        PushMessage pushMessage = new PushMessage();
        pushMessage.setTag(BoxName.CLUB.value() + System.currentTimeMillis());
        Alert alert = new Alert();
        alert.setBody("俱乐部消息：" + msg);
        pushMessage.setAlert(alert);
        List<Integer> to = new ArrayList<Integer>();
        to.add(currentUid);//推送给报名活动的人
        pushMessage.setTo(to);
        pushMessage.setLogo(LARK_LOGO);
        pushMessage.setLogoUrl("");
        Payload payload = new Payload();
        payload.setBoxType(BoxType.CLUB_MSG.value());
        payload.setMsgType(MsgType.JUMP_MSG.value());
        payload.setTitle(msg);
        //俱乐部LOGO
        TbClub tbClub = clubMapper.selectByPrimaryKey(respClubActivity.getClubId());
        payload.setImg(tbClub.getLogoUrl());
        //当前时间
        payload.setTimestamp(System.currentTimeMillis());
        payload.setUrl("/api/club/activity/activityDetail");      //跳转到俱乐部活动详情页
        Jump jump = new Jump();
        jump.setIdType(IdType.CLUB_ACTIVITY_DETAIL_PAGE.value());
        Map<String, Object> jumMap = new HashMap<>();
        jumMap.put("activityId", activityId);
        jump.setParam(jumMap);
        payload.setJump(jump);
        pushMessage.setPayload(payload);
        reqPushMessage.setMsgList(Arrays.asList(pushMessage));
        reqPushMessage.setAppId(larkAppId);
        this.pushMsg(reqPushMessage);
    }

    /**
     * 用户取消报名费用到账通知
     * @param respClubActivity
     * @param orderUid
     */
    @Async
    @Override
    public void pushRefundActivityOrder(RespClubActivity respClubActivity,
                                        Integer orderUid, String businessOrderNo)
    {
        //推送内容
        respClubActivity.getLogoUrl();
        String msg = "您申请的" + respClubActivity.getName() + "订单退款已成功到账，请留意查收！";
        ReqPushMessage reqPushMessage = new ReqPushMessage();
        PushMessage pushMessage = new PushMessage();
        pushMessage.setTag(BoxName.CLUB.value() + System.currentTimeMillis());
        Alert alert = new Alert();
        alert.setBody("俱乐部消息：" + msg);
        pushMessage.setAlert(alert);
        List<Integer> to = new ArrayList<Integer>();
        to.add(orderUid);//推送给发布俱乐部活动的人
        pushMessage.setTo(to);
        pushMessage.setLogo(LARK_LOGO);
        pushMessage.setLogoUrl("");
        Payload payload = new Payload();
        payload.setBoxType(BoxType.CLUB_MSG.value());
        payload.setMsgType(MsgType.JUMP_MSG.value());
        payload.setTitle(msg);
        //俱乐部LOGO
        payload.setImg(respClubActivity.getLogoUrl());
        //当前时间
        payload.setTimestamp(System.currentTimeMillis());
        payload.setUrl("/api/club/activity/activityOrderDetail");      //跳转到俱乐部活动订单详情页
        Jump jump = new Jump();
        jump.setIdType(IdType.CLUB_ACTIVITY_ORDER_DETAIL_PAGE.value());
        Map<String, Object> jumMap = new HashMap<>();
        jumMap.put("activityId", respClubActivity.getActivityId());
        jumMap.put("businessOrderNo", businessOrderNo);
        jump.setParam(jumMap);
        payload.setJump(jump);
        pushMessage.setPayload(payload);
        reqPushMessage.setMsgList(Arrays.asList(pushMessage));
        this.pushMsg(reqPushMessage);
    }

    /**
     * 活动发布时通知俱乐部的所有成员
     */
    @Override
    public void pushCreateActivity(RespClubActivity respClubActivity) {
        //推送内容
        respClubActivity.getLogoUrl();
        String msg = "您加入的“" + respClubActivity.getClubName() + "”俱乐部刚刚发布了“" +
                respClubActivity.getName() + "”活动，快去参加吧！";
        ReqPushMessage reqPushMessage = new ReqPushMessage();
        PushMessage pushMessage = new PushMessage();
        pushMessage.setTag(BoxName.CLUB.value() + System.currentTimeMillis());
        Alert alert = new Alert();
        alert.setBody("俱乐部消息：" + msg);
        pushMessage.setAlert(alert);
        //推送给俱乐部的所有成员
        TbClubMemberExample tbClubMemberExample = new TbClubMemberExample();
        TbClubMemberExample.Criteria criteria = tbClubMemberExample.createCriteria();
        criteria.andClubIdEqualTo(respClubActivity.getClubId());
        List<TbClubMember> tbClubMembers = clubMemberMapper.selectByExample(tbClubMemberExample);
        List<Integer> to = new ArrayList<Integer>();
        for (TbClubMember tbClubMember : tbClubMembers) {
            if(tbClubMember.getUid().intValue() != respClubActivity.getUid())
            {
                to.add(tbClubMember.getUid());
            }
        }
        pushMessage.setTo(to);
        pushMessage.setLogo(LARK_LOGO);
        pushMessage.setLogoUrl("");
        Payload payload = new Payload();
        payload.setBoxType(BoxType.CLUB_MSG.value());
        payload.setMsgType(MsgType.JUMP_MSG.value());
        payload.setTitle(msg);
        //俱乐部LOGO
        payload.setImg(respClubActivity.getLogoUrl());
        //当前时间
        payload.setTimestamp(System.currentTimeMillis());
        payload.setUrl("/api/club/activity/activityDetail");      //跳转到俱乐部活动详情页
        Jump jump = new Jump();
        jump.setIdType(IdType.CLUB_ACTIVITY_DETAIL_PAGE.value());
        Map<String, Object> jumMap = new HashMap<>();
        jumMap.put("activityId", respClubActivity.getActivityId());
        jump.setParam(jumMap);
        payload.setJump(jump);
        pushMessage.setPayload(payload);
        reqPushMessage.setMsgList(Arrays.asList(pushMessage));
        this.pushMessageToC(reqPushMessage);
    }


    /**
     * 批量推送
     * @param reqPushMessage
     */
    private void pushMessageToC(ReqPushMessage reqPushMessage){
        List<PushMessage> msgList=reqPushMessage.getMsgList();
        for (PushMessage pu:msgList){
            List<Integer> to=pu.getTo();
            int pageSize = 40;
            int pageCount = to.size()/pageSize;
            for (int i = 0; i < pageCount; i++) {
                int pageNum = i + 1;
                Limit limit = Limit.buildLimit(pageNum, pageSize);
                int start = limit.getStart();
                logger.warn("发布活动推送通知：" + start + "," + limit.getStart() + pageSize);
                List<Integer> users = to.subList(start, start + pageSize - 1);
                logger.warn("users:" + users);
                pu.setTo(users);
                reqPushMessage.setMsgList(Arrays.asList(pu));
                this.pushMsg(reqPushMessage);
            }
            int last = to.size()%pageSize;
            if(last > 0){
                logger.warn("发布活动推送通知：" + pageCount*pageSize + "," + last);
                int fromIndex = pageCount*pageSize > last ? last:pageCount*pageSize;
                List<Integer> users = to.subList(pageCount*pageSize, pageCount*pageSize + last);
                logger.warn("users:" + users);
                pu.setTo(users);
                reqPushMessage.setMsgList(Arrays.asList(pu));
                this.pushMsg(reqPushMessage);
            }
        }
    }

    /**
     * 活动修改时通知参加该活动的成员
     */
    @Async
    @Override
    public void pushUpdateActivity(RespClubActivity respClubActivity) {
        //推送内容
        respClubActivity.getLogoUrl();
        String msg = "您报名参加的活动“" + respClubActivity.getName() +
                "”，俱乐部管理员已进行了修改，赶快去看看吧。";
        ReqPushMessage reqPushMessage = new ReqPushMessage();
        PushMessage pushMessage = new PushMessage();
        pushMessage.setTag(BoxName.CLUB.value() + System.currentTimeMillis());
        Alert alert = new Alert();
        alert.setBody("俱乐部消息：" + msg);
        pushMessage.setAlert(alert);
        //推送给参加该活动的成员
        TbSignUserExample example = new TbSignUserExample();
        TbSignUserExample.Criteria criteria = example.createCriteria();
        criteria.andActivityIdEqualTo(respClubActivity.getActivityId());
        criteria.andIsCancelEqualTo(0);//未取消
        criteria.andStatusEqualTo(1);//有效
        List<TbSignUser> tbSignUserList = signUserMapper.selectByExample(example);
        List<Integer> to = new ArrayList<Integer>();
        for (TbSignUser tbSignUser : tbSignUserList) {
            if (tbSignUser.getIsReplace() != 0 || tbSignUser.getManageType().intValue() == 5) {
                //补报名和代报名人没有uid
                continue;
            }
            if(null == tbSignUser.getOrderUserId())
            {
                continue;
            }
            to.add(tbSignUser.getOrderUserId());
        }
        pushMessage.setTo(to);
        pushMessage.setLogo(LARK_LOGO);
        pushMessage.setLogoUrl("");
        Payload payload = new Payload();
        payload.setBoxType(BoxType.CLUB_MSG.value());
        payload.setMsgType(MsgType.JUMP_MSG.value());
        payload.setTitle(msg);
        payload.setTitle(msg);
        //俱乐部LOGO
        payload.setImg(respClubActivity.getLogoUrl());
        //当前时间
        payload.setTimestamp(System.currentTimeMillis());
        payload.setUrl("/api/club/activity/activityDetail");      //跳转到俱乐部活动详情页
        Jump jump = new Jump();
        jump.setIdType(IdType.CLUB_ACTIVITY_DETAIL_PAGE.value());
        Map<String, Object> jumMap = new HashMap<>();
        jumMap.put("activityId", respClubActivity.getActivityId());
        jump.setParam(jumMap);
        payload.setJump(jump);
        pushMessage.setPayload(payload);
        reqPushMessage.setMsgList(Arrays.asList(pushMessage));
        this.pushMessageToC(reqPushMessage);
    }

    /**
     * 已报名的活动在结束后推送
     */
    @Override
    public void pushActivityEndingMsg(int activityId, String logoUrl, int feeType,
                                      String posterUrl, String name) {

        String msg = "您报名参加的活动“" + name +
                "”已经结束，您对活动还满意吗？来评价一下吧！";
        //推送给参加该活动的成员
        TbSignUserExample example = new TbSignUserExample();
        TbSignUserExample.Criteria criteria = example.createCriteria();
        criteria.andActivityIdEqualTo(activityId);
        criteria.andIsCancelEqualTo(0);//未取消
        criteria.andManageTypeEqualTo(4);//签到
        criteria.andStatusEqualTo(1);//有效
        List<TbSignUser> tbSignUserList = signUserMapper.selectByExample(example);
        List<Integer> to = new ArrayList<Integer>();
        Map<Integer, String> orderUser = new HashMap<Integer, String>();
        for (TbSignUser tbSignUser : tbSignUserList) {
            if (tbSignUser.getIsReplace() != 0 || tbSignUser.getManageType().intValue() == 5) {
                //补报名和代报名人没有uid
                continue;
            }
            if(null != tbSignUser.getOrderId() && null != tbSignUser.getOrderUserId())
            {
                to.add(tbSignUser.getOrderUserId());
                TbOrder order = orderMapper.selectByPrimaryKey(tbSignUser.getOrderId());
                orderUser.put(tbSignUser.getOrderUserId(), order.getOrderNo());
            }

        }
        int pageSize = 40;
        int pageCount = to.size()/pageSize;
        for (int i = 0; i < pageCount; i++) {

            int pageNum = i + 1;
            Limit limit = Limit.buildLimit(pageNum, pageSize);
            int start = limit.getStart();
            logger.warn("推送报名人评价页面：" + start + "," + limit.getStart() + pageSize);
            List<Integer> users = to.subList(start, start + pageSize - 1);
            for(Integer id : users)
            {
                if(null != id && id != 0)
                {
                    pushToAppriase(activityId, logoUrl, feeType,
                            posterUrl, name, msg, Arrays.asList(id), orderUser.get(id));
                }
            }
        }
        int last = to.size()%pageSize;
        if(last > 0)
        {
            logger.warn("推送报名人评价页面：" + pageCount*pageSize + "," + last);
            List<Integer> users = to.subList(pageCount*pageSize, pageCount*pageSize + last);
            logger.warn("users:" + users);
            for(Integer id : users)
            {
                if(null != id && id != 0)
                {
                    pushToAppriase(activityId, logoUrl, feeType,
                            posterUrl, name, msg, Arrays.asList(id), orderUser.get(id));
                }
            }
        }
    }

    public void pushToAppriase(int activityId, String logoUrl, int feeType, String posterUrl,
                               String name, String msg, List<Integer> to, String orderNo)
    {
        ReqPushMessage reqPushMessage = new ReqPushMessage();
        PushMessage pushMessage = new PushMessage();
        pushMessage.setTag(BoxName.CLUB.value() + System.currentTimeMillis());
        Alert alert = new Alert();
        alert.setBody("俱乐部消息：" + msg);
        pushMessage.setAlert(alert);
        pushMessage.setTo(to);
        pushMessage.setLogo(LARK_LOGO);
        pushMessage.setLogoUrl("");
        Payload payload = new Payload();
        payload.setBoxType(BoxType.CLUB_MSG.value());
        payload.setMsgType(MsgType.JUMP_MSG.value());
        payload.setTitle(msg);
        //俱乐部LOGO
        payload.setImg(logoUrl);
        //当前时间
        payload.setTimestamp(System.currentTimeMillis());
        Jump jump = new Jump();
        Map<String, Object> jumMap = new HashMap<>();
        payload.setUrl("");
        jump.setIdType(IdType.CLUB_ACTIVITY_APPRAISE_PAGE.value());  //跳转到活动评价页面
        jumMap.put("activityId", activityId);
        jumMap.put("activityName", name);
        jumMap.put("activityLogoURL", posterUrl);
        jumMap.put("businessOrderNo", orderNo);
        jump.setParam(jumMap);
        payload.setJump(jump);
        pushMessage.setPayload(payload);
        reqPushMessage.setMsgList(Arrays.asList(pushMessage));
        this.pushMsg(reqPushMessage);
    }

    private void pushMsg(ReqPushMessage reqPushMessage) {
        try {
            String postJson = JSON.toJSONString(reqPushMessage);
            logger.warn("推送消息：" + postJson);
            String result = HttpClientUtils.postJson(messagePushServiceUrl, postJson);
            logger.warn("推送返回：" + result);
        } catch (Exception e) {
            logger.error("推送消息失败，" + e.getMessage());
        }
    }

    @Async
    @Override
    public void pushActivityAppraise(ActivityRelatedMsg activityRelatedMsg) {

        TbClub club = clubMapper.selectByPrimaryKey(activityRelatedMsg.getClubId());
        if (club == null) return;

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(activityRelatedMsg.getUserNick())
                .append("评价了你在俱乐部“")
                .append(club.getClubName())
                .append("“发布的活动”")
                .append(activityRelatedMsg.getActivityName())
                .append("“，快去看看吧！");

        String message = stringBuilder.toString();

        ReqPushMessage reqPushMessage = new ReqPushMessage();
        PushMessage pushMessage = new PushMessage();
        pushMessage.setTag(BoxName.CLUB.value() + System.currentTimeMillis());
        Alert alert = new Alert();
        alert.setBody("俱乐部消息：" + message);
        pushMessage.setAlert(alert);

        pushMessage.setTo(activityRelatedMsg.getToUid());
        pushMessage.setLogo(LARK_LOGO);
        pushMessage.setLogoUrl("");
        Payload payload = new Payload();
        payload.setBoxType(BoxType.CLUB_MSG.value());
        payload.setMsgType(MsgType.JUMP_MSG.value());
        payload.setTitle(message);
        payload.setImg(activityRelatedMsg.getAvatar());
        payload.setTimestamp(System.currentTimeMillis());

        payload.setUrl("/api/club/comment/list");         //评论列表
        Jump jump = new Jump();
        jump.setIdType(IdType.CLUB_ACTIVITY_APPRAISE_LIST.value());
        Map<String, Object> jumMap = new HashMap<>();
        jumMap.put("clubId", activityRelatedMsg.getClubId());
        jumMap.put("pageNum", 0);
        jumMap.put("pageSize", 20);
        jump.setParam(jumMap);
        payload.setJump(jump);

        pushMessage.setPayload(payload);
        reqPushMessage.setMsgList(Arrays.asList(pushMessage));

        this.pushMsg(reqPushMessage);
    }

    @Override
    public void pushActivitySignUpSuccess(ActivityRelatedMsg activityRelatedMsg) {

        TbClub club = clubMapper.selectByPrimaryKey(activityRelatedMsg.getClubId());
        if (club == null) return;

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(activityRelatedMsg.getUserNick())
                .append("参加了你在俱乐部“")
                .append(club.getClubName())
                .append("”发布的活动“")
                .append(activityRelatedMsg.getActivityName())
                .append("”");

        String message = stringBuilder.toString();

        ReqPushMessage reqPushMessage = new ReqPushMessage();
        PushMessage pushMessage = new PushMessage();
        pushMessage.setTag(BoxName.CLUB.value() + System.currentTimeMillis());
        Alert alert = new Alert();
        alert.setBody("俱乐部消息：" + message);
        pushMessage.setAlert(alert);

        pushMessage.setTo(activityRelatedMsg.getToUid());
        pushMessage.setLogo(LARK_LOGO);
        pushMessage.setLogoUrl("");
        Payload payload = new Payload();
        payload.setBoxType(BoxType.CLUB_MSG.value());
        payload.setMsgType(MsgType.JUMP_MSG.value());
        payload.setTitle(message);
        payload.setImg(activityRelatedMsg.getAvatar());
        payload.setTimestamp(System.currentTimeMillis());

        payload.setUrl("/api/club/activity/activityMemberList");         //活动成员列表
        Jump jump = new Jump();
        jump.setIdType(IdType.CLUB_MEMBER_LIST_PAGE.value());
        Map<String, Object> jumMap = new HashMap<>();
        jumMap.put("activityId", activityRelatedMsg.getActivityId());
        jumMap.put("pageNo", 1);
        jumMap.put("pageSize", 20);
        jump.setParam(jumMap);
        payload.setJump(jump);

        pushMessage.setPayload(payload);
        reqPushMessage.setMsgList(Arrays.asList(pushMessage));

        this.pushMsg(reqPushMessage);
    }

    @Override
    public void pushActivitySettlement(ActivityRelatedMsg activityRelatedMsg,
                                       RespClubFinanceBillDetail respClubFinanceBillDetail) {

        TbClub club = clubMapper.selectByPrimaryKey(activityRelatedMsg.getClubId());
        if (club == null)
        {
            logger.warn("没有这个俱乐部,req:" + activityRelatedMsg.getClubId());
            return;
        }

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("你在俱乐部“")
                .append(club.getClubName())
                .append("”发布的活动“")
                .append(activityRelatedMsg.getActivityName())
                .append("”已经成功结算");

        String message = stringBuilder.toString();

        ReqPushMessage reqPushMessage = new ReqPushMessage();
        PushMessage pushMessage = new PushMessage();
        pushMessage.setTag(BoxName.CLUB.value() + System.currentTimeMillis());
        Alert alert = new Alert();
        alert.setBody("俱乐部消息：" + message);
        pushMessage.setAlert(alert);

        pushMessage.setTo(activityRelatedMsg.getToUid());
        pushMessage.setLogo(LARK_LOGO);
        pushMessage.setLogoUrl("");
        Payload payload = new Payload();
        payload.setBoxType(BoxType.CLUB_MSG.value());
        payload.setMsgType(MsgType.JUMP_MSG.value());
        payload.setTitle(message);
        payload.setImg(club.getLogoUrl());
        payload.setTimestamp(System.currentTimeMillis());

        payload.setUrl("");         //活动账单详情
        Jump jump = new Jump();
        jump.setIdType(IdType.ACTIVITY_ACCOUNT_DETAIL.value());
        Map<String, Object> jumMap = new HashMap<>();
        jumMap.put("serialNo", respClubFinanceBillDetail.getSerialNo());
        jumMap.put("amount", respClubFinanceBillDetail.getAmount());
        jumMap.put("onlineAmount", respClubFinanceBillDetail.getOnlineAmount());
        jumMap.put("offlineAmount", respClubFinanceBillDetail.getOfflineAmount());
        jumMap.put("activityId", respClubFinanceBillDetail.getActivityId());
        jumMap.put("activityName", respClubFinanceBillDetail.getActivityName());
        jumMap.put("incomeFrom", respClubFinanceBillDetail.getIncomeFrom());
        jumMap.put("numberOfPeople", respClubFinanceBillDetail.getNumberOfPeople());
        jumMap.put("createTime", respClubFinanceBillDetail.getCreateTime());
        jumMap.put("createrName", respClubFinanceBillDetail.getCreaterName());
        if(null != activityRelatedMsg.getPosterId())
        {
            TbActivityPoster poster =
                    tbActivityPosterMapper.selectByPrimaryKey(activityRelatedMsg.getPosterId());
            jumMap.put("avatar", poster.getUrl());
        }
        jump.setParam(jumMap);
        payload.setJump(jump);

        pushMessage.setPayload(payload);
        reqPushMessage.setMsgList(Arrays.asList(pushMessage));

        this.pushMsg(reqPushMessage);
    }

    /**
     * 管理员线下给成员充值扣费消息推送
     */
    @Async
    @Override
    public void pushOfflineRechargeDebutMsg(int clubId, int uid, BigDecimal amount, BigDecimal usableAmount, String remark, boolean recharge) {

        TbClub club = clubMapper.selectByPrimaryKey(clubId);
        String msg = "";
        if (recharge) {
            msg = "您在俱乐部“" + club.getClubName() + "”的账户已充值" + amount.doubleValue() + "元，当前余额为" + usableAmount.doubleValue() + "元。";
        } else {
            msg = "您在俱乐部“" + club.getClubName() + "”的账户已扣费" + amount.doubleValue() + "元，当前余额为" + usableAmount.doubleValue() + "元。" + remark;
        }
        ReqPushMessage reqPushMessage = new ReqPushMessage();
        PushMessage pushMessage = new PushMessage();
        pushMessage.setTag(BoxName.CLUB.value() + System.currentTimeMillis());
        Alert alert = new Alert();
        alert.setBody("俱乐部消息：" + msg);
        pushMessage.setAlert(alert);
        pushMessage.setTo(Arrays.asList(uid));
        Payload payload = new Payload();
        payload.setBoxType(BoxType.CLUB_MSG.value());
        payload.setMsgType(MsgType.JUMP_MSG.value());
        payload.setTitle(msg);
        payload.setBody("");
        payload.setImg(club.getLogoUrl());
        payload.setTimestamp(System.currentTimeMillis());
        payload.setUrl("/api/club/fmg/memberRemainder");      //跳转到俱乐部活动详情页
        Jump jump = new Jump();
        jump.setIdType(IdType.CLUB_MEMBER_ACCOUNT_PAGE.value());
        Map<String, Object> jumMap = new HashMap<>();
        jumMap.put("clubId", club.getId());
        jumMap.put("uid", uid);
        jumMap.put("controllerStyle", 2);
        jump.setParam(jumMap);
        payload.setJump(jump);
        pushMessage.setPayload(payload);
        reqPushMessage.setMsgList(Arrays.asList(pushMessage));
        this.pushMsg(reqPushMessage);
    }

    /**
     * 推送俱乐部公告信息
     * @param clubId
     * @param content
     * @param title
     * @param club
     */
    @Async
    @Override
    public void pushClubAnnouncement(Integer clubId,String content,String title,TbClub club){
        TbClubMemberExample example = new TbClubMemberExample();
        example.createCriteria().andClubIdEqualTo(clubId).andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbClubMember> clubMemberList = this.clubMemberMapper.selectByExample(example);

        for (TbClubMember clubMember : clubMemberList) {
            List<Integer> uidList = new ArrayList<>();
            uidList.add(clubMember.getUid());
            ReqPushMessage reqPushMessage = new ReqPushMessage();
            PushMessage pushMessage = new PushMessage();
            pushMessage.setTag(BoxName.CLUB.value()+System.currentTimeMillis());
            Alert alert = new Alert();
            alert.setBody("俱乐部通告：" + content);
            pushMessage.setAlert(alert);

            pushMessage.setTo(uidList);
            pushMessage.setLogo(LARK_LOGO);
            pushMessage.setLogoUrl("");
            Payload payload = new Payload();
            payload.setBoxType(BoxType.CLUB_MSG.value());

            payload.setMsgType(MsgType.JUMP_MSG.value());

            StringBuffer sb = new StringBuffer();
            sb.append("【公告】").append(club.getClubName()).append(":").append(title);
            payload.setTitle(sb.toString());

            payload.setBody(content);
            payload.setImg(club.getLogoUrl());
            payload.setTimestamp(System.currentTimeMillis());

            Jump jump = new Jump();
            jump.setIdType(IdType.CLUB_ANNOUNCEMENT_PAGE.value());
            Map<String, Object> jumMap = new HashMap<>();
            jumMap.put("clubId",clubId);
            jumMap.put("roleCode",clubMember.getRoleCode());
            jump.setParam(jumMap);
            payload.setJump(jump);
            pushMessage.setPayload(payload);
            reqPushMessage.setMsgList(Arrays.asList(pushMessage));

            try {
                String postJson = JSON.toJSONString(reqPushMessage);
                logger.info("推送公告消息：" + postJson);
                String result = HttpClientUtils.postJson(messagePushServiceUrl, postJson);
                logger.info("推送返回：" + result);
            } catch (Exception e) {
                logger.info("推送消息失败，" + e.getMessage());
            }
        }
    }

    public void pushAdminDeleteClub(Integer clubId)
    {
        TbClub club = clubMapper.selectByPrimaryKey(clubId);
        String msg = "你的“" + club.getClubName() +
                "”俱乐部因违法平台规定，已经暂停运营，如有疑问请联系客服。”";
        ReqPushMessage reqPushMessage = new ReqPushMessage();
        PushMessage pushMessage = new PushMessage();
        pushMessage.setTag(BoxName.CLUB.value() + System.currentTimeMillis());
        Alert alert = new Alert();
        alert.setBody("俱乐部消息：" + msg);
        pushMessage.setAlert(alert);
        Payload payload = new Payload();
        payload.setBoxType(BoxType.CLUB_MSG.value());
        payload.setMsgType(MsgType.NOTIFY_MSG.value());
        payload.setTitle(msg);
        payload.setImg(club.getLogoUrl());
        payload.setTimestamp(System.currentTimeMillis());
        pushMessage.setPayload(payload);
        pushMessage.setTo(Arrays.asList(club.getUid()));
        reqPushMessage.setMsgList(Arrays.asList(pushMessage));
        this.pushMsg(reqPushMessage);
    }

    /**
     * 解散俱乐部消息
     */
    public void pushDisableClub(Integer clubId, List<Integer> to){
        TbClub club = clubMapper.selectByPrimaryKey(clubId);
        String msg = club.getClubName() + "俱乐部解散了！";
        ReqPushMessage reqPushMessage = new ReqPushMessage();
        PushMessage pushMessage = new PushMessage();
        pushMessage.setTag(BoxName.CLUB.value() + System.currentTimeMillis());
        Alert alert = new Alert();
        alert.setBody("俱乐部消息：" + msg);
        pushMessage.setAlert(alert);
        Payload payload = new Payload();
        payload.setBoxType(BoxType.CLUB_MSG.value());
        payload.setMsgType(MsgType.NOTIFY_MSG.value());
        payload.setTitle(msg);
        payload.setImg(club.getLogoUrl());
        payload.setTimestamp(System.currentTimeMillis());
        pushMessage.setPayload(payload);
        pushMessage.setTo(to);
        reqPushMessage.setMsgList(Arrays.asList(pushMessage));
        this.pushMsg(reqPushMessage);
    }

    public void pushAdminDeleteClubActivity(Integer activityId)
    {
        logger.warn("activityId:" + activityId);
        TbClubActivityExample tbClubActivityExample = new TbClubActivityExample();
        tbClubActivityExample.createCriteria().andActivityIdEqualTo(activityId);
        List<TbClubActivity> clubActivitys = tbclubActivityMapper.selectByExample(tbClubActivityExample);
        ActivityInfo activityInfo = activityOpenService.selectOneActivityById(activityId);
        if(null == clubActivitys || clubActivitys.size() == 0)
        {
            return;
        }
        TbClubActivity clubActivity = clubActivitys.get(0);
        TbClub club = clubMapper.selectByPrimaryKey(clubActivity.getClubId());
        String msg = "你的“" + club.getClubName() + "”俱乐部发的”" + activityInfo.getName()
                + "“活动因违法平台规定，已经删除，如有疑问请联系客服。";
        ReqPushMessage reqPushMessage = new ReqPushMessage();
        PushMessage pushMessage = new PushMessage();
        pushMessage.setTag(BoxName.CLUB.value() + System.currentTimeMillis());
        Alert alert = new Alert();
        alert.setBody("俱乐部消息：" + msg);
        pushMessage.setAlert(alert);
        Payload payload = new Payload();
        payload.setBoxType(BoxType.CLUB_MSG.value());
        payload.setMsgType(MsgType.NOTIFY_MSG.value());
        payload.setTitle(msg);
        payload.setImg(club.getLogoUrl());
        payload.setTimestamp(System.currentTimeMillis());
        pushMessage.setPayload(payload);
        pushMessage.setTo(Arrays.asList(clubActivity.getUid()));
        reqPushMessage.setMsgList(Arrays.asList(pushMessage));
        this.pushMsg(reqPushMessage);

    }

    @Override
    public void pushClubTaskNotify(String taskName, Map<Integer, Integer> clubIdUidMap, Map<Integer, String> clubIdLogoMap) {
        String msg = "恭喜您收到"+ taskName + "奖励任务！快去您的俱乐部主页看下吧！";
        ReqPushMessage reqPushMessage = new ReqPushMessage();
        List<PushMessage> pushMessages = new ArrayList<>();

        Set<Integer> keySet = clubIdUidMap.keySet();
        for (Integer clubId : keySet) {
            PushMessage pushMessage = new PushMessage();
            pushMessage.setTag(BoxName.CLUB.value() + System.currentTimeMillis());
            Alert alert = new Alert();
            alert.setBody("俱乐部消息：" + msg);
            pushMessage.setAlert(alert);
            Payload payload = new Payload();
            payload.setBoxType(BoxType.CLUB_MSG.value());
            payload.setMsgType(MsgType.NOTIFY_MSG.value());
            payload.setTitle(msg);
            payload.setImg(clubIdLogoMap.get(clubId));
            payload.setTimestamp(System.currentTimeMillis());
            pushMessage.setPayload(payload);
            pushMessage.setTo(Arrays.asList(clubIdUidMap.get(clubId)));

            pushMessages.add(pushMessage);
        }

        reqPushMessage.setMsgList(pushMessages);
        this.pushMsg(reqPushMessage);

    }

    @Async
    @Override
    public void pushClubCommonMsg(String clubLog, String msg, List<Integer> to) {
        logger.warn("入参：" + clubLog + ",msg:" + msg + "users:" + JSONObject.toJSON(to));
        ReqPushMessage reqPushMessage = new ReqPushMessage();
        List<PushMessage> pushMessages = new ArrayList<>();

        PushMessage pushMessage = new PushMessage();
        pushMessage.setTag(BoxName.CLUB.value() + System.currentTimeMillis());
        Alert alert = new Alert();
        alert.setBody("俱乐部消息：" + msg);
        pushMessage.setAlert(alert);
        Payload payload = new Payload();
        payload.setBoxType(BoxType.CLUB_MSG.value());
        payload.setMsgType(MsgType.NOTIFY_MSG.value());
        payload.setTitle(msg);
        payload.setImg(clubLog);
        payload.setTimestamp(System.currentTimeMillis());
        pushMessage.setPayload(payload);
        pushMessage.setTo(to);

        pushMessages.add(pushMessage);

        reqPushMessage.setMsgList(pushMessages);
        this.pushMsg(reqPushMessage);
    }

    @Async
    @Override
    public void pullClubSuccess2DrawAward(String logo, String msg, List<Integer> to){

        ReqPushMessage reqPushMessage = new ReqPushMessage();
        List<PushMessage> pushMessages = new ArrayList<>();

        PushMessage pushMessage = new PushMessage();
        pushMessage.setTag(BoxName.CLUB.value() + System.currentTimeMillis());
        Alert alert = new Alert();
        alert.setBody("俱乐部消息：" + msg);
        pushMessage.setAlert(alert);
        Payload payload = new Payload();
        payload.setBoxType(BoxType.CLUB_MSG.value());
        payload.setMsgType(MsgType.NOTIFY_MSG.value());
        payload.setTitle(msg);
        payload.setImg(logo);
        payload.setTimestamp(System.currentTimeMillis());

        Jump jump = new Jump();
        jump.setIdType(IdType.CLUB_DRAW_AWARD_H5_PAGE.value());
        Map<String, Object> jumMap = new HashMap<>();
        jump.setParam(jumMap);
        payload.setJump(jump);

        pushMessage.setPayload(payload);
        pushMessage.setTo(to);

        pushMessages.add(pushMessage);

        reqPushMessage.setMsgList(pushMessages);
        this.pushMsg(reqPushMessage);
    }
}
